Here are the main rules of Promises in JavaScript:
Immutable State Once Settled
A promise can have one of three states:
Thenable Behavior
A promise can be chained using .then()
:
.then(onFulfilled, onRejected)
– Executes the appropriate callback when the promise settles..then()
callback returns a value, the next .then()
receives that value..then()
callback throws an error or returns a rejected promise, the next .catch()
is triggered.Chaining
A promise can be chained:
Error Propagation
.then()
callback throws an error, it is propagated down the chain to the nearest .catch()
.Microtask Queue
No Side Effects on Rejection Without Catch
.catch()
or try...catch
is attached, it results in an unhandled promise rejection.Promise Resolution Rules
Example:
In this example:
then
receives the resolved value.reject
is called instead, catch
will handle the error.